package com.example.securitydemo1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.securitydemo1.entity.Users;
import com.example.securitydemo1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * ClassName: UserService
 * Package: com.example.securitydemo1.service
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-05-29
 * Time: 13:30
 */
@Service("userDetailsService")
public class UserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用方法查询数据库 根据用户名查询
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",username);
        Users users = userMapper.selectOne(queryWrapper);
        //判断
        if (users == null){ //那么验证失败
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale");

        //从数据库中查询到user 然后返回

        //第三个参数是权限 是一个集合  不能为空  在这个Users查询出来的用户就有这个权限
        return new User(users.getName(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);

    }
}
